package com.seedeer.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.seedeer.common.util.AuthorityUtils;
import com.seedeer.pms.model.PmsAccountInfo;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 常用字段填充器
 *
 * @author wangqiang
 **/
@Component
public class FieldHandler implements MetaObjectHandler {
    /**
     * 插入元对象字段填充（用于插入时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        PmsAccountInfo pmsAccountInfo = AuthorityUtils.getCurrentUser();
        if(pmsAccountInfo != null){
            String userCode = pmsAccountInfo.getUserCode();
            Object createUser = getFieldValByName("createUser", metaObject);
            if(createUser == null){
                this.strictInsertFill(metaObject, "createUser", String.class, userCode);
            }
            Object updateUser = getFieldValByName("updateUser", metaObject);
            if(updateUser == null){
                this.strictInsertFill(metaObject, "updateUser", String.class, userCode);
            }//test
        }

        Object createTime = getFieldValByName("createTime", metaObject);
        if(createTime == null){
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        }
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if(updateTime == null){
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }

    /**
     * 更新元对象字段填充（用于更新时对公共字段的填充）
     *
     * @param metaObject 元对象
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        PmsAccountInfo pmsAccountInfo = AuthorityUtils.getCurrentUser();
        if(pmsAccountInfo != null){
            String userCode = pmsAccountInfo.getUserCode();
            Object updateUser = getFieldValByName("updateUser", metaObject);
            if(updateUser == null){
                this.strictInsertFill(metaObject, "updateUser", String.class, userCode);
            }
        }
        Object updateTime = getFieldValByName("updateTime", metaObject);
        if(updateTime == null){
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        }
    }
}
